<template>
  <div class="userEidt">
    <p class="titleadd">{{ showEid ? '组织新增' : '组织编辑' }}</p>
    <div class="eidtform">
      <el-form :model="form" label-width="100px" :rules="dataFormRules" ref="form" class="addForm">
        <el-form-item label="组名称" prop="name">
          <el-input v-model="form.name" auto-complete="off" clearable></el-input>
        </el-form-item>
        <!-- :rules="[
            { type: 'number', message: '必须为数字值' }
        ]"-->
        <el-form-item label="组织代码" prop="organs">
          <el-input v-model="form.organs" auto-complete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" auto-complete="off" clearable></el-input>
        </el-form-item>
<!--        <el-form-item label="群号 " prop="group">-->
<!--          <el-input v-model="form.group" auto-complete="off" clearable></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="简介 " prop="des">
          <el-input v-model="form.des" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" auto-complete="off"
                    clearable maxlength="200" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="地址 " prop="address">
          <el-input v-model="form.address" auto-complete="off" clearable></el-input>
        </el-form-item>
<!--        <el-form-item label="管理小区" prop="CODES">-->
<!--          <el-select v-model="form.CODES" placeholder="请选择" multiple filterable clearable>-->
<!--            <el-option v-for="item in options" :key="item.CID" :label="item.name" :value="item.CID"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="机构图片" prop="imgs">
          <div class="row">
            <el-image @click="deleteImg(item, index, 'imgs')" v-for="(item, index) in form.imgs" :key="index"
                      :src="getItemPhoto(item)" class="el-upload--picture-card mr20"></el-image>

            <el-upload ref="uploadImg" :show-file-list="false" action="#" list-type="picture-card"
                       :http-request="handleUpLoad" :beforeUpload="beforeAvatarUpload">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <i style="color: red" class="tishi">上传小于10MB图片</i>
          </div>
        </el-form-item>
        <el-form-item label="地图经度">
          <el-input class="mapinp" v-model="form.longitude" auto-complete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="地图经度">
          <el-input class="mapinp" v-model="form.latitude" auto-complete="off" clearable></el-input>
          <!-- <span>大小：</span>
            <el-input
              class="mapnum"
              v-model="form.zooms"
              placeholder="1~4"
              auto-complete="off"
              clearable
            ></el-input> -->
        </el-form-item>
      </el-form>
      <div class="subbtn">
        <el-button @click.native="cancelbut">清空</el-button>
        <el-button type="primary" @click.native="submitForm">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import Guan from '@/components/business/GuanliPeople';
import { getBase64 } from '@/common/utils';
export default {
  components: {
    Guan,
  },
  props: {
    showEid: {
      type: Boolean,
      default: true
    },
    dataForm: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      form: {
        name: '',
        organs: '',
        phone: '',
        des: '',
        address: '',
        CODES: '',
        imgs: [],
        photos: [],
        longitude: '',
        latitude: '',
        zooms: '',
      },
      options: [],
      organization: [],
      dataFormRules: {
        name: [
          {
            required: true,
            message: '组名称不能为空',
            trigger: 'blur'
          }
        ],
        // encoded: [,
        type: [
          {
            required: true,
            message: '类型不能为空',
            trigger: 'blur'
          }
        ],
        CODES: [
          {
            required: false,
            message: '管理小区不能为空',
            trigger: 'blur'
          }
        ]
      },
      isShow: true
    };
  },
  watch: {
    dataForm(v) {
      if (v) {
        this.isShow = false;
        this.form = {
          name: '',
          organs: '',
          phone: '',
          des: '',
          address: '',
          CODES: '',
          imgs: [],
          photos: [],
          longitude: '',
          latitude: '',
          zooms: ''
        };
        Object.assign(this.form, v);
      }
      setTimeout(() => {
        this.isShow = true;
      }, 100);
      this.$forceUpdate();
    }
  },
  mounted() {
    this.getCommunity();
  },
  methods: {
    // 地图传过来的值
    getlocat(lng, lat) {
      this.form.longitude = lng;
      this.form.latitude = lat;
    },
    // 获取面数据
    getarea(val) {
      this.form.area = [];
      val.forEach(item => {
        this.form.area.push([item.lng, item.lat]);
      });
    },
    // 拼接图片
    getItemPhoto(id) {
      var url = this.global.baseUrlImage + 'avatar/' + id;
      return url;
    },

    // 网格图片上传
    async handleUpLoad(param) {
      // 文件流处理获取 base64格式图片数据 存储到 imgup中
      let imgup = await getBase64(param.file);

      this.uploadFileImg(imgup, 'imgs');
    },
    // 网格图片上传
    async handleUpLoad1(param) {
      // 文件流处理获取 base64格式图片数据 存储到 imgup中
      let imgup = await getBase64(param.file);

      this.uploadFileImg(imgup, 'photos');
    },
    uploadFileImg(img, name) {
      this.$api.imgAdd
        .addimgPer({ img })
        .then(res => {
          if (res.code == 0) {
            let arr = this.form[name].concat([res.id]);
            this.$set(this.form, name, arr);
            console.log(this.form[name]);
          } else {
            this.$message({
              message: res.msg + '服务器报错',
              type: 'info'
            });
          }
        })
        .catch(err => {
          this.$message({
            message: err + '添加报错',
            type: 'info'
          });
        });
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message({
          message: '上传图片大小不能超过 10MB!',
          type: 'warning'
        });
      }
      return isLt2M;
    },
    //   删除图片
    deleteImg(item, index, name) {
      this.$confirm('确认删除此照片吗？', '提示', {}).then(() => {
        this.form[name].splice(index, 1);
      });
    },

    // 获取小区
    getCommunity() {
      let dictList = JSON.parse(sessionStorage.getItem('dictData'));
      this.organization = dictList.sys_organization_type;
      let params = {
        where: { CODES: [] }
      };
      let param = JSON.stringify(params);
      this.$api.dept.getCommunityList(param).then(res => {
        if (res.code == 0) {
          this.options = res.data;
        } else {
          this.$message({
            message: '操作失败, ' + res.msg,
            type: 'error'
          });
        }
      });
    },

    submitForm: function() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            let params = {
              rows: this.form,
              where: { GID: this.form.GID }
            };
            let paramJson = JSON.stringify(params);
            this.$api.dept.save(paramJson).then(res => {
              if (res.code == 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.dialogVisible = false;
                this.$refs['form'].resetFields();
                this.$refs.uploadImg.clearFiles();
                this.$emit('clickCancel');
              } else {
                this.$message({
                  message: '操作失败, ' + res.msg,
                  type: 'error'
                });
              }
            });
          });
        }
      });
    },
    //   清空
    cancelbut() {
      this.$refs['form'].resetFields();
      this.$refs.uploadImg.clearFiles();
    }
  }
};
</script>

<style lang="scss" scoped>
.userEidt {
  height: 100%;
  overflow: hidden;
}

.titleadd {
  top: 0;
  line-height: 50px;
  padding: 0 20px;
  border-left: 5px solid rgb(30, 175, 243);
  margin-bottom: 20px;
}

.eidtform {
  margin: 0 auto;
  height: 90%;
  overflow-y: auto;

  .subbtn {
    margin: 20px auto;
    width: 200px;
  }
}

.addForm {
  padding-left: 40px;
  box-sizing: border-box;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: start;

  .el-form-item {
    width: 45%;
    margin-bottom: 40px;
  }
}

</style>
